package com.kashow.base;

/**
 * Created by yybs on 16/11/17.
 */

import com.google.gson.JsonObject;
import com.kashow.C;
import com.kashow.base.rx.RxManager;
import com.kashow.bean.message.unread.chat.BaseChat;
import com.kashow.bean.message.unread.chat.Message;
import com.kashow.base.utilsJsonUtil;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * Created by yybs on 16/11/17.
 */
@Singleton
public class ChatSocketManager {
    private Socket mSocket;
    private boolean isConnected;
    private boolean initSuccess = true;
    private boolean initEvent = false;
    private RxManager mRxManager;
    private String mUserId;
    private String mUserName;
    private String mUserAvatar;

    @Inject
    public ChatSocketManager(RxManager rxManager, Socket socket) {
        mRxManager = rxManager;
        mSocket = socket;
        if (mSocket != null) {
            initSuccess = true;
        }
        init();
    }


    public void join(String userId,String userName,String userAvatar) {
        this.mUserId = userId;
        this.mUserName = userName;
        this.mUserAvatar = userAvatar;
        if (isConnected) {
            JsonObject object = new JsonObject();
            object.addProperty("userId", mUserId);
            object.addProperty("headimgurl", mUserAvatar);
            object.addProperty("userName", mUserName);
            mSocket.emit(C.SOCKET.JOIN_CHAT, object);
        }
    }

    public void sendMessage(JsonObject to, String content) {
        if (isConnected) {
            JsonObject object = new JsonObject();
            object.addProperty("from", mUserId);
            object.add("to", to);
            object.addProperty("content", content);
            mSocket.emit(C.SOCKET.SEND_CHAT, object);
        }
    };

    public void connect() {
        if (mSocket != null && !mSocket.connected()) {
            mSocket.connect();
        }
    }

    public void init() {
        if (!initEvent) {
            mSocket.on(Socket.EVENT_CONNECT, onConnect);
            mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
            mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
            mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
            mSocket.on(C.SOCKET.SEND_CHAT,onMessage);
            initEvent = true;
        }
    }

    public void unInit() {
        mSocket.disconnect();
        if (initEvent) {
            mSocket.off(Socket.EVENT_CONNECT, onConnect);
            mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
            mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
            mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
            mSocket.off(C.SOCKET.SEND_MESSAGE,onMessage);
            initEvent = false;
        }
        isConnected = false;
    }


    private Emitter.Listener onMessage = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            JSONObject data = (JSONObject) args[0];
            Logger.d("onMessage ---->%s",data.toString());
            BaseChat baseChat = JsonUtil.fromJson(data.toString(),Message.class);
            if (mUserId.equals(baseChat.getFrom().getUserId())) {
                baseChat.setItemType(BaseChat.MESSAGE_SEND);
            } else {
                baseChat.setItemType(BaseChat.MESSAGE_RECEIVE);
            }
            mRxManager.post(C.SOCKET.SEND_CHAT,baseChat);
        }
    };


    private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            if(!isConnected) {
                mRxManager.post(Socket.EVENT_CONNECT,Socket.EVENT_CONNECT);
                isConnected = true;
            }
        }
    };

    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Logger.d("onDisconnect");
            mRxManager.post(Socket.EVENT_DISCONNECT,Socket.EVENT_DISCONNECT);
            isConnected = false;
        }
    };

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Logger.d("onConnectError");
            mRxManager.post(Socket.EVENT_CONNECT_ERROR,Socket.EVENT_CONNECT_ERROR);
            isConnected = false;
        }
    };
}

